package com.edu.base.common.upload;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.nio.channels.FileChannel;

import javax.servlet.http.HttpServletResponse;

import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;


/**
 * 描述：多功能上传类
 * @author hzl
 *
 */
public class UploadFileUtils  {

	
	public static final String separator = File.separator;
	/**
	 * 可选: local,aliyun,qiniu
	 */
	protected static String type = "local";
	/**
	 * 描述：上传单个普通文件
	 * @param single
	 * @return 文件访问路径
	 * @throws IOException
	 */
	public static String singleSave(MultipartFile single){
		String saveUrl = "";
		try {
			FileService fileService = getTypeFileService();
			saveUrl = fileService.singleFile(single);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return saveUrl;
	}
	/**
	 * 描述：上传单个普通文件
	 * @param path:路径
	 * @param bl:false，在项目根路径下附加path路径,true:完全使用传入的路径
	 * @param single
	 * @return 文件访问路径
	 * @throws IOException
	 */
	public static String singleSave(MultipartFile single,String path,boolean bl){
		String saveUrl = "";
		try {
			FileService fileService = getTypeFileService();
			saveUrl = fileService.singleFile(single,path,bl);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return saveUrl;
	}
	/**
	 * 描述：上传多个普通文件
	 * @param path:路径
	 * @param bl:false，在项目根路径下附加path路径,true:完全使用传入的路径
	 * @param multiple
	 * @return str[0] 第一个文件 str[1]第二个文件
	 * @throws IOException
	 */
	public static String[] multipleSave(MultipartFile[] multiple,String path,boolean bl) {
		String[] str = null;
		try {
			FileService fileService = getTypeFileService();
			str = fileService.multipleFile(multiple, path, bl);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return str;
	}
	/**
	 * 描述：上传多个普通文件
	 * @param multiple
	 * @return str[0] 第一个文件 str[1]第二个文件
	 * @throws IOException
	 */
	public static String[] multipleSave(MultipartFile[] multiple) {
		String[] str = null;
		try {
			FileService fileService = getTypeFileService();
			str = fileService.multipleFile(multiple);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return str;
	}
	/**
	 * 描述：上传单个视频文件
	 * @param single
	 * @return str[0] 文件路径 str[1] 缩略图路径
	 * @throws IOException
	 */
	public static String[] singleVideoSave(MultipartFile single) {
		String[] str = null;
		try {
			FileService fileService = getTypeFileService();
			str = fileService.singleVideoFile(single);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return str;
	}
	
	public static String getType() {
		return type;
	}
	public static void setType(String type) {
		UploadFileUtils.type = type;
	}
	/**
	 * 获取不同的上传实现类
	 * @return
	 */
	private static FileService getTypeFileService() {
		FileService fileService = null;
		if("local".equals(type)){
			fileService = new LocalFileServiceImpl();
		}else if("aliyun".equals(type)) {
			fileService = new AliyunFileServiceImpl();
		}else if("qiniu".equals(type)) {
			fileService = new QiniuFileServiceImpl();
		}
		return fileService;
	}
	
	/**
	 * 描述：下载网络文件，通常用在阿里云图片的下载到客户端
	 * @param dirPath 文件绝对地址
	 */
	public static void downNetFile(HttpServletResponse response,String urlPath,String fileName){
        try {
            // path是指欲下载的文件的路径。
        	// 构造URL    
            URL url = new URL(urlPath);  
            // 打开连接    
            URLConnection con = url.openConnection();    
            //设置请求超时为5s    
            con.setConnectTimeout(2000000*1000);    
            // 取得文件名。
            String _filename = url.getFile();
            // 取得文件的后缀名。
            if(StringUtils.isEmpty(fileName)){
            	fileName=StringUtils.getFilename(_filename);
            }else{
            	 String ext = _filename.substring(_filename.lastIndexOf("."));
                 fileName = fileName + ext;
            }

            // 以流的形式下载文件。
            // 输入流    
            InputStream is = con.getInputStream();    
            // 1K的数据缓冲 
            byte[] buffer = new byte[is.available()];
            is.read(buffer);
            is.close();
            // 清空response
            response.reset();
            // 设置response的Header
            response.setContentType("application/octet-stream; charset=utf-8");
            response.addHeader("Content-Disposition","attachment;filename=\""+ new String(fileName.getBytes("GB2312"),"iso8859-1")+  "\"") ;
          //  response.addHeader("content-disposition","attachment;filename*=UTF-8‘‘" + URLEncoder.encode(fileName, "UTF-8"));
           
          //  response.addHeader("Content-Disposition", "attachment;filename=" + fileName);
            response.addHeader("Content-Length", "" +buffer.length);
            OutputStream toClient = new BufferedOutputStream(response.getOutputStream());

            toClient.write(buffer);
            toClient.flush();
            toClient.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
		        
	}
	
	/**
	 * 描述：下载文件
	 * @param dirPath 文件绝对地址
	 */
	public static void downFile(HttpServletResponse response,String dirPath,String fileName){
        try {
            // path是指欲下载的文件的路径。
            File file = new File(dirPath);
            // 取得文件名。
            String _filename = file.getName();
            // 取得文件的后缀名。
            String ext = _filename.substring(_filename.lastIndexOf("."));
            fileName = fileName + ext;
            // 以流的形式下载文件。
            InputStream fis = new BufferedInputStream(new FileInputStream(file));
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();
            // 清空response
            response.reset();
            // 设置response的Header
            response.setContentType("application/octet-stream; charset=utf-8");
            response.addHeader("Content-Disposition","attachment;filename=\""+ new String(fileName.getBytes("GB2312"),"iso8859-1")+  "\"") ;
          //  response.addHeader("content-disposition","attachment;filename*=UTF-8‘‘" + URLEncoder.encode(fileName, "UTF-8"));
           
          //  response.addHeader("Content-Disposition", "attachment;filename=" + fileName);
            response.addHeader("Content-Length", "" + file.length());
            OutputStream toClient = new BufferedOutputStream(response.getOutputStream());

            toClient.write(buffer);
            toClient.flush();
            toClient.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
		        
	}
}
